<?php

class Acesso {

	private $login;
	private $classe;
	private $pathToTemplate;

	public function __construct( $user = "", $pass = "", $pathToTemplate = "content/login/loginForm.php" ) {

		$this->login = new Login();

		$this->pathToTemplate = $pathToTemplate;

		if ( @$_COOKIE['usuario'] && @$_COOKIE['senha'] )
		{
			$this->login->user = $_COOKIE['usuario'];
			$this->login->pass = $_COOKIE['senha'];
			$md5 = 0;
		}
		
		elseif ( @$_SESSION['usuario'] && @$_SESSION['senha'] )
		{
			$this->login->user = $_SESSION['usuario'];
			$this->login->pass = $_SESSION['senha'];
			$md5 = 0;
		}
		
		elseif ( @$_POST['usuario'] && @$_POST['senha'] )
		{
			$this->login->user = $_POST['usuario'];
			$this->login->pass = $_POST['senha'];
			$md5 = 1;
		}

		else return;

		$seguranca = new Seguranca( $this->login->user );
		$this->login->user = $seguranca->getValor();
		$seguranca = new Seguranca( $this->login->pass, $md5 );
		$this->login->pass = $seguranca->getValor();

	}

	public function logar() {

		if ( !$this->login->user || !$this->login->pass ) 
		{
			$this->loginForm();
			return new Usuario( new Login() );
		}

		$banco = DataBase::getBanco();
		$row = $banco->query("SELECT * FROM usuario WHERE ( login_usuario = '" . $this->login->user . "' OR email_usuario = '" . $this->login->user . "' ) AND senha_usuario = '" . $this->login->pass . "' ");
		
		if ( $banco->error ) 
			echo $banco->error . "<br />";

		$row = $row->fetch_object();
		if ( @$row->id_usuario )
		{
			$this->setCredentials( $row );
			return new Usuario( $this->login );
		}

		$this->loginForm();

		return new Usuario( new Login() );
	}

	private function setCredentials( $row ) {

		//Mantém o usuario logado
		if ( @$_POST['conectado'] )
		{
			setcookie( 'usuario', $row->login_usuario );
			setcookie( 'senha', $row->senha_usuario );
		}
		else
		{
			$_SESSION['usuario'] = $row->login_usuario;
			$_SESSION['senha'] = $row->senha_usuario;				
		}

		//Seta os dados de login
		$this->login->user = $row->login_usuario ;
		$this->login->pass = $row->senha_usuario;
		$this->login->id = $row->id_usuario;
		$this->login->classe = $row->tipo_usuario;

	}

	public function deslogar() {

		$_POST['usuario'] = "";
		$_POST['senha'] = "";
		setcookie( 'usuario' );
		setcookie( 'senha' );
		$_SESSION['usuario'] = "";
		$_SESSION['senha'] = "";

	}
	public function loginForm() {

		$this->deslogar();

		include( $this->pathToTemplate );

	}

	public function esqueciSenha() {
		echo "Under Construction!";
	}

}

?>